Prime Numbers

76

prime numbers -

#include <iostream>
#include <cmath>
#include <iostream>

#define el "\n"

using namespace std;

bool isprime(int n)
{
    if (n <= 1)
    {
        return 0;
    }
 
    for(int i=2 ; i <= sqrt(n); i++) // [sqrt(n)] is faster in calculations than [n/2]
    {
        if(n%i == 0)
        {
            return 0;
        }
    }
    return 1;
};

int main() 
{
    long long num;

    cin >> num; // ~~~ Enter a number
 
    (isprime(num))? cout << "The number (" << num <<") is a prime" << el : cout << "The number (" << num <<") isn't a prime" << el;
        
    return 0;
}

prime number -

def is_prime(n):
  if(n<0):
    print("n is not a nature number!")
    return False
  for i in range(1,ceil(n/2)+1):
    if (i != n and i != 1 and n%i == 0):
      return False
  return True
print(is_prime(int(input("number>>"))))

Prime Numbers -

using System;
public class Program
{
    static void Main(string[] args)
    {
        var results = GenerateSieve(1000);
        var i=0;
        foreach (var item in results)
        {
            if(item) Console.Write(i + " ");
            i++;
        }
    }
 
    static bool[] GenerateSieve(int num)
    {
        // Creating an array indicating whether numbers are prime.
        bool[] isPrime = new bool[num + 1];
        for (int i = 2; i <= num; i++) isPrime[i] = true;
 
        // Removing out multiples.
        for (int i = 2; i <= num; i++)
        {
            // Check if i is prime.
            if (isPrime[i])
            {
                // Eliminate multiples of i.
                for (int j = i * 2; j <= num; j += i)
                    isPrime[j] = false;
            }
        }
        return isPrime;
    }
}

Comments

Submit
0 Comments